from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String
from config import SQLALCHEMY_DATABASE_URI, POOL_SIZE, MAX_OVERFLOW
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()


def get_mysql_engine():
    engine = create_engine(SQLALCHEMY_DATABASE_URI,
                           pool_size=POOL_SIZE,
                           max_overflow=MAX_OVERFLOW,
                           pool_recycle=7200
                           )
    return engine


def get_mysql_session(engine):
    session = scoped_session(sessionmaker(bind=engine))
    return session


class Game(Base):
    __tablename__ = 'game'
    name = Column(String(255), primary_key=True)
    rating = Column(String(20))

    @classmethod
    def add_game_info(cls, **kwargs):
        engine = get_mysql_engine()
        session = get_mysql_session(engine)
        try:
            filter_list = []
            filter_list.append(cls.name==kwargs.get('name'))
            contactinfo_model = session.query(cls.name).filter(*filter_list)
            if contactinfo_model.first():
                contactinfo_model.update(kwargs)
                print('更新成功')
            else:
                contactinfo_model = Game(
                    name=kwargs.get('name'),
                    rating=kwargs.get('rating'),
                )
                session.add(contactinfo_model)
                print("新增数据成功")
            session.commit()
        except Exception as e:
            session.rollback()
            print('数据库异常，更新失败')
            print(e.args)
            return {'message': '数据库异常，更新失败', 'error': e.args}
        finally:
            engine.dispose()
            session.remove()
        return {'message': 'OK'}